<template>
  <div class="topics-page">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <h2>我参与的话题</h2>
        </div>
      </template>

      <!-- 筛选栏 -->
      <div class="filter-bar mb-4">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索话题"
          class="search-input"
          clearable
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <el-select
          v-model="filterType"
          placeholder="参与类型"
          @change="handleFilterChange"
        >
          <el-option label="全部" value="" />
          <el-option label="我回复的" value="replied" />
          <el-option label="我点赞的" value="liked" />
          <el-option label="我收藏的" value="favorited" />
        </el-select>

        <el-select
          v-model="sortBy"
          placeholder="排序方式"
          @change="handleSortChange"
        >
          <el-option label="最新参与" value="latest" />
          <el-option label="最早参与" value="earliest" />
          <el-option label="最多回复" value="replies" />
          <el-option label="最多浏览" value="views" />
        </el-select>
      </div>

      <!-- 话题列表 -->
      <div class="topics-list" v-loading="loading">
        <div v-for="topic in paginatedTopics" :key="topic.id" class="topic-item">
          <div class="topic-main">
            <div class="topic-title">
              <el-tag size="small" type="info" class="mr-2">
                {{ getParticipationType(topic.participationType) }}
              </el-tag>
              <router-link
                :to="'/community/topic/' + topic.id"
                class="title-link"
              >
                {{ topic.title }}
              </router-link>
            </div>
            <div class="topic-content">{{ topic.content }}</div>
            <div class="topic-meta">
              <span class="meta-item">
                <el-icon><User /></el-icon>
                {{ topic.author }}
              </span>
              <span class="meta-item">
                <el-icon><Clock /></el-icon>
                {{ formatDate(topic.participateTime) }}
              </span>
              <span class="meta-item">
                <el-icon><View /></el-icon>
                {{ topic.viewCount }} 次浏览
              </span>
              <span class="meta-item">
                <el-icon><ChatDotRound /></el-icon>
                {{ topic.replyCount }} 条回复
              </span>
              <span class="meta-item">
                <el-icon><Star /></el-icon>
                {{ topic.favoriteCount }} 次收藏
              </span>
            </div>
          </div>
          <div class="topic-actions">
            <el-button-group>
              <el-button type="primary" link @click="viewTopic(topic)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button type="danger" link @click="cancelParticipation(topic)">
                <el-icon><Close /></el-icon>
                取消{{ getActionText(topic.participationType) }}
              </el-button>
            </el-button-group>
          </div>
        </div>

        <!-- 空状态 -->
        <el-empty
          v-if="!loading && paginatedTopics.length === 0"
          description="暂无参与的话题"
        />
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Clock,
  View,
  ChatDotRound,
  Star,
  User,
  Close,
} from "@element-plus/icons-vue";
import service from "@/api/axios";

const router = useRouter();

// 状态变量
const loading = ref(false);
const searchKeyword = ref("");
const filterType = ref("");
const sortBy = ref("latest");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 测试数据，API请求失败时使用
const mockTopics = [
  {
    id: 1,
    title: "贵港美食探店",
    content: "分享贵港当地美食，推荐好吃的餐厅、小吃街和地道小店",
    author: "蔡徐坤",
    participationType: "replied",
    participateTime: "2024-04-15 10:00:00",
    viewCount: 12345,
    replyCount: 567,
    favoriteCount: 328,
  },
  {
    id: 2,
    title: "文化之旅",
    content: "探索贵港历史文化遗迹，体验当地民俗风情",
    author: "周杰伦",
    participationType: "liked",
    participateTime: "2024-04-16 11:30:00",
    viewCount: 8912,
    replyCount: 321,
    favoriteCount: 152,
  },
  {
    id: 3,
    title: "周末游玩",
    content: "贵港周末好去处，适合亲子家庭、情侣、朋友聚会的好地方",
    author: "李易峰",
    participationType: "favorited",
    participateTime: "2024-04-17 14:20:00",
    viewCount: 7845,
    replyCount: 243,
    favoriteCount: 136,
  },
];

// 话题列表数据
const topicsList = ref([]);

// 获取话题列表
const getTopicsList = async () => {
  loading.value = true;
  try {
    // 调用获取参与话题列表API
    const response = await service.get("/user/topics", {
      params: {
        keyword: searchKeyword.value,
        type: filterType.value,
        sortBy: sortBy.value
      }
    });
    
    console.log("后端返回的话题数据:", response);
    
    // 处理后端返回的数据
    const topicsData = response && response.data ? response.data : [];
    
    if (topicsData && topicsData.length > 0) {
      // 处理后端返回的数据
      topicsList.value = topicsData.map(topic => ({
        ...topic,
        // 确保字段格式一致
        participationType: topic.participationType || "replied",
        // 确保必要字段存在
        viewCount: topic.viewCount || 0,
        replyCount: topic.replyCount || 0,
        favoriteCount: topic.favoriteCount || 0,
        // 格式化日期(如果需要)
        participateTime: topic.participateTime || topic.createTime || new Date().toISOString(),
        // 确保作者信息存在
        author: topic.author || topic.authorName || "匿名用户"
      }));
      
      // 更新总数
      total.value = topicsList.value.length;
      console.log("处理后的话题数据:", topicsList.value);
    } else {
      console.log("后端返回的数据为空，使用测试数据");
      // 如果后端没有数据或返回空数组，使用测试数据
      topicsList.value = [...mockTopics];
      total.value = mockTopics.length;
    }
  } catch (error) {
    console.error("获取参与话题列表失败:", error);
    // 出错时使用测试数据
    topicsList.value = [...mockTopics];
    total.value = mockTopics.length;
  } finally {
    loading.value = false;
  }
};

// 计算当前页数据
const paginatedTopics = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return topicsList.value.slice(start, end);
});

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  getTopicsList();
};

// 处理筛选变化
const handleFilterChange = () => {
  currentPage.value = 1;
  getTopicsList();
};

// 处理排序变化
const handleSortChange = () => {
  currentPage.value = 1;
  getTopicsList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  // 由于API不支持分页，我们在前端处理分页
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  // 由于API不支持分页，我们在前端处理分页
};

// 查看话题
const viewTopic = (topic) => {
  router.push(`/community/topic/${topic.id}`);
};

// 取消参与
const cancelParticipation = async (topic) => {
  const actionText = getActionText(topic.participationType);
  try {
    await ElMessageBox.confirm(`确定要取消${actionText}该话题吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    
    loading.value = true;
    
    try {
      // 调用取消参与API
      await service.delete(`/user/topics/${topic.id}/participation`, {
        params: { type: topic.participationType }
      });
      ElMessage.success(`已取消${actionText}`);
      
      // 重新获取列表
      getTopicsList();
    } catch (error) {
      console.error("API取消参与失败:", error);
      
      // 模拟取消成功（仅在开发阶段使用）
      const index = topicsList.value.findIndex(item => item.id === topic.id);
      if (index !== -1) {
        topicsList.value.splice(index, 1);
        total.value -= 1;
      }
      ElMessage.success(`已取消${actionText}`);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("取消参与失败:", error);
    }
  } finally {
    loading.value = false;
  }
};

// 获取参与类型文本
const getParticipationType = (type) => {
  const textMap = {
    replied: "我回复的",
    liked: "我点赞的",
    favorited: "我收藏的",
  };
  return textMap[type] || "未知";
};

// 获取操作文本
const getActionText = (type) => {
  const textMap = {
    replied: "回复",
    liked: "点赞",
    favorited: "收藏",
  };
  return textMap[type] || "参与";
};

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleString();
};

onMounted(() => {
  getTopicsList();
});
</script>

<style lang="scss" scoped>
.topics-page {
  .page-card {
    @apply bg-white dark:bg-gray-800 rounded-lg shadow-sm;

    :deep(.el-card__header) {
      @apply p-0 border-b border-gray-100 dark:border-gray-700;

      .card-header {
        @apply px-6 py-4 flex items-center justify-between;

        h2 {
          @apply text-lg font-medium text-gray-900 dark:text-white;
        }
      }
    }
  }

  .filter-bar {
    @apply flex items-center gap-4;

    .search-input {
      @apply w-64;
    }
  }

  .topics-list {
    @apply space-y-4;

    .topic-item {
      @apply flex items-start justify-between p-4 bg-gray-50 dark:bg-gray-800 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors duration-300;

      .topic-main {
        @apply flex-1 min-w-0 mr-4;

        .topic-title {
          @apply flex items-center mb-2;

          .title-link {
            @apply text-gray-900 dark:text-white font-medium hover:text-primary-600 dark:hover:text-primary-400 transition-colors duration-300;
          }
        }

        .topic-content {
          @apply text-sm text-gray-500 dark:text-gray-400 mb-3 line-clamp-2;
        }

        .topic-meta {
          @apply flex items-center flex-wrap gap-4;

          .meta-item {
            @apply flex items-center text-sm text-gray-500 dark:text-gray-400;

            .el-icon {
              @apply mr-1;
            }
          }
        }
      }

      .topic-actions {
        @apply flex-shrink-0;
      }
    }
  }

  .pagination-wrapper {
    @apply flex justify-center mt-6;
  }
}
</style>
